package com.dacd.soundanalysis.thread

import android.content.Context
import android.util.Log
import com.alibaba.fastjson.JSON
import com.dacd.soundanalysis.bean.SoundBean
import com.dacd.soundanalysis.filehelper.FileConstants
import com.dacd.soundanalysis.filehelper.FileHelper
import java.io.File
import java.util.*
import java.util.Collections.swap
import kotlin.collections.ArrayList

/**
 * 合成需要对比的素材
 */
class SynthesisThread(context: Context, recordList: ArrayList<SoundBean>): Thread() {

    private var recordList: ArrayList<SoundBean>? = null
    private var context:Context? = null

    init {
        this.recordList = recordList
        this.context = context
    }

    override fun run() {
        val recordDir = File(context!!.cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR)//存放音频的文件夹
        if (!recordDir.exists()) {//如果文件夹不存在，说明没有保存过文件，直接保存素材文件
            val record = JSON.toJSON(recordList).toString()
            val fileName = "record"
            FileHelper.saveFile(context!!.cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR,
                fileName, record)
            return
        }
        //文件夹存在，继续判断文件是否存在
        val recordFile = File(context!!.cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR, "record")//存放音频的文件夹
        if (!recordFile.exists()) {//如果文件不存在直接保存
            val record = JSON.toJSON(recordList).toString()
            val fileName = "record"
            FileHelper.saveFile(context!!.cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR,
                fileName, record)
            return
        }
        //如果文件也存在那么开始进行合成
        val localFileRecList = JSON.parseArray(File(recordFile.absolutePath).readText(), SoundBean::class.java)
        recordList!!.addAll(localFileRecList)
        recordList!!.sortBy { it.timeMillis }
        val headList = ArrayList<SoundBean>()
        val iterator = recordList!!.iterator()
        while (iterator.hasNext()) {
            val soundBean = iterator.next()
            if(soundBean.isHead) {
                headList.add(soundBean)
                iterator.remove()
            }
        }
        for (soundBean in headList) {
            recordList!!.add(0, soundBean)
        }
        val record = JSON.toJSON(recordList).toString()
        val fileName = "record"
        FileHelper.saveFile(context!!.cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR,
            fileName, record)
    }


}